import { createRouter, createWebHistory } from "vue-router";
import homeRoutes from "./home";
import consoleRoutes from "./console";
const appRoutes = [
    {
        path: "/",
        redirect: "/home"
    },
    {
        path: "/login",
        name: "Login",
        component: () => import("@/views/Login.vue"),
        meta: { title: "登录" }
    },
    ...homeRoutes,
    ...consoleRoutes,
    {
        path: "/error/:code",
        name: "Error",
        component: () => import("@/components/Error/Error.vue"),
        meta: {
            title: "出错啦！",
        },
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/error/404'
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes: appRoutes,
    scrollBehavior(_to, _from, savedPosition) {
        if (savedPosition) {
            return savedPosition; // 页面滚动到之前的位置
        } else {
            return { top: 0, left: 0 }; // 页面滚动到顶部
        }
    },
});


router.afterEach((to) => {
    // 页面标题
    document.title = !to.meta.title ? import.meta.env.VITE_APP_TITLE : to.meta.title + " · " + import.meta.env.VITE_APP_TITLE;
});

export const getRouterPaths = (menuRouter: any[]) => {
    const paths = [] as string[];
    menuRouter.forEach(e => {
        if (e.path) {
            paths.push(e.path);
        }
        if (e.children) {
            paths.push(...getRouterPaths(e.children));
        }
    });
    return paths;
};
// 路由菜单权限控制
const whiteList = ['/login'];


const isWhitePath = (path: string) => {
    if (whiteList.includes(path)) {
        return true;
    }
    if (path.startsWith('/error/')) {
        return true;
    }

    return false;
};

// 路由守卫
router.beforeEach((to, from, next) => {
    logger("路由" + from.path + "切换至:", to.path);
    const userStore = useUserStore();

    if (import.meta.env.DEV) {
        next();
        return;
    }
    if (isWhitePath(to.path)) {
        next();
        return;
    }
    if (!userStore.isLogin) {
        next('/login');
        return;
    }
    // if (!userStore.hasPermission(to.meta.roles)) {
    //   // Message.error('没有权限访问该页面');
    //   next('/error/403');
    //   return;
    // }
    next();
});


export default router;
